package com.cx.base.day13_io.io_03_bufferStream;

import java.io.*;

/**
 * @Author: robert.song
 * @Date: Created in 2022/4/22
 */
public class BufferedInputStream2OutputStream {
    public static void main(String[] args) throws IOException {
        baseByteBuffer();
    }

    public static void baseByteBuffer() throws IOException {
        File file1 = new File("." + properties() + "test0.txt");
        File file2 = new File("." + properties() + "test5.txt");
//        如果文件没有上级目录，获取父级目录，然后执行mkdirs()
        file1.getParentFile().mkdirs();
        file2.getParentFile().mkdirs();
        file1.createNewFile();
        file2.createNewFile();
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2, true);
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int len = 0;
        try {
            long start = System.currentTimeMillis();
            while ((len = bis.read(b)) != -1) {
//          底层默认设置了8k的缓存，缓存满了刷新磁盘，
//          缓冲流可在创建时自定义缓冲区大小，用数组实现
//          文件流的底层是用户态的缓冲区，即Buffer对象
                bos.write(b, 0, len);
//            很明显这种情况是大数据量的流，不推荐再频繁执行flush()刷新磁盘
//            bos.flush();
            }
            System.out.println(System.currentTimeMillis() - start);
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }

    }

    public static String properties() throws IOException {
        return System.getProperty("file.separator");
    }
}
